package com.example.demo.utils;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.mapper.OperteLogMapper;
import com.example.demo.pojo.emp.OperateLog;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 切面类
 *
 * */
@Component
@Aspect //定义是一个切面类
public class AopLogAspect {

    @Autowired
    private HttpServletRequest request;//获取此次请求的请求对象  就可以拿到对应的请求头等信息
    @Autowired
    private OperteLogMapper operteLogMapper;


    //匹配方法上有Log注解的方法
    @Around("@annotation(com.example.demo.annotate.Log)")
    public Object recordLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        //操作人----当前登录人的用户名   获取请求头中的令牌 解析令牌
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.JwtParse(jwt);

        String operateUser = (String) claims.get("username");
        LocalDateTime operateTime = LocalDateTime.now();
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        String methodName = proceedingJoinPoint.getSignature().getName();

        Object result = proceedingJoinPoint.proceed();
        String returnValue = JSONObject.toJSONString(result);

        OperateLog operateLog = new OperateLog(null,operateUser,operateTime,className,methodName,null,returnValue,null);
        operteLogMapper.insert(operateLog);
        System.out.println("111111"+operateLog);
        return result;
    }
}
